package com.example.a22310.myapplication.Activity;


import android.Manifest;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.SyncStateContract;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.example.a22310.myapplication.Abstractclass.ImageBaseActivity;
import com.example.a22310.myapplication.Photo.Base64;
import com.example.a22310.myapplication.Photo.PhotoUtils;
import com.example.a22310.myapplication.ViewModel.User.AlterInformationViewModel;
import com.example.a22310.myapplication.ViewModel.User.GetUserInformationViewModel;
import com.example.a22310.myapplication.ViewModel.User.UserInformationViewModel;
import com.example.a22310.myapplication.ViewModel.User.UserPostViewModel;
import com.example.a22310.myapplication.databinding.ActivityUserInformationBinding;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class UserInformation extends ImageBaseActivity {
    private ActivityUserInformationBinding binding;
    private int userid;
    int REQUEST_CODE = 1;
    private static final int CODE_GALLERY_REQUEST = 0xa0;
    private static final int CODE_CAMERA_REQUEST = 0xa1;
    private static final int CODE_RESULT_REQUEST = 0xa2;
    private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/photo.png");
    private File fileCropUri = new File(Environment.getExternalStorageDirectory().getPath() + "/crop_photo.png");
    private Uri imageUri;
    private Uri cropImageUri;
    private Double latitude,longitude;//经纬度
    private  Bitmap bitmap;
    private String FILENAME = "yuejian'data";
    private String imgBase64;
     File file  = null ;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_user_information);
        SharedPreferences sharedPreferences = getSharedPreferences("yuejian'data", this.MODE_PRIVATE);
        userid = sharedPreferences.getInt("userId",2);
        //由于数据不完全，当前用默认的id=2;
        new UserInformationViewModel(this, binding,userid);
        new UserPostViewModel(this,binding,userid);
        new GetUserInformationViewModel(this,binding,userid);

        binding.alterUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String address = longitude+"|"+latitude;

                try {
                    file = new File(new URI(cropImageUri.toString()));
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
                RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                MultipartBody.Part body = MultipartBody.Part.createFormData("pic", file.getName(),requestBody);

            new AlterInformationViewModel(UserInformation.this,binding,getUserid(),binding.name.getText().
                    toString(),address,body);



                System.out.println("---------->>>>>>>>>>>>"+file);

            }
        });

        binding.usrImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alterUserDialog();
            }
        });

    }



    /***********************
  ****** 获取用户id******
  ***********************/
    private int  getUserid(){
        int newsNumber;
        SharedPreferences sharedPreferences = getSharedPreferences(FILENAME, Context.MODE_PRIVATE);
        newsNumber = sharedPreferences.getInt("userId",0);
        return newsNumber;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        int output_X = 480, output_Y = 480;
        if (requestCode == REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                Bundle bundle = data.getExtras();
                if (bundle != null) {
                    binding.address.setText(bundle.getString("address"));
                }
                latitude = bundle.getDouble("latitude");
                longitude= bundle.getDouble("longitude");
              //  System.out.println("-------------------->>>"+latitude+"//////"+longitude);
            }
        }
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CODE_CAMERA_REQUEST://拍照完成回调
                    cropImageUri = Uri.fromFile(fileCropUri);
                    PhotoUtils.cropImageUri(this, imageUri, cropImageUri, 1, 1, output_X, output_Y, CODE_RESULT_REQUEST);
                    break;
                case CODE_GALLERY_REQUEST://访问相册完成回调
                    if (hasSdcard()) {
                        cropImageUri = Uri.fromFile(fileCropUri);
                        Uri newUri = Uri.parse(PhotoUtils.getPath(this, data.getData()));
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                            newUri = FileProvider.getUriForFile(this, "lc305.zx323.yuejian.fileprovider", new File(newUri.getPath()));
                        PhotoUtils.cropImageUri(this, newUri, cropImageUri, 1, 1, output_X, output_Y, CODE_RESULT_REQUEST);
                    } else {
                        Toast.makeText(UserInformation.this, "设备没有SD卡!", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case CODE_RESULT_REQUEST:
                    bitmap = PhotoUtils.getBitmapFromUri(cropImageUri, this);
                    if (bitmap != null) {
                        byte[] img;

                        img = getBitmapByte(bitmap);

                        imgBase64 = Base64.encodeBytes(img);

                        binding.usrImg.setImageBitmap(bitmap);
                    }
                    break;
            }
        }
        if(requestCode == SyncStateContract.Constants.REQUEST_API) {
            if(resultCode == SyncStateContract.Constants.REQUEST_LOGIN) {
                Tencent.handleResultData(data,  new ShareUiListener(UserInformation.this));
            }
        }
    }

    public void alterUserDialog() {
        FragmentManager fragmentManager = getFragmentManager();
        UserDailog userDailog = new UserDailog();
        userDailog.show(fragmentManager, "hello,tomorrow!");
    }

    public void takePictureInCamera(){
        requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, new ImageBaseActivity.RequestPermissionCallBack() {
            @Override
            public void granted() {
                if (hasSdcard()) {
                    imageUri = Uri.fromFile(fileUri);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                        //通过FileProvider创建一个content类型的Uri
                        imageUri = FileProvider.getUriForFile(UserInformation.this, "lc305.zx323.yuejian.fileprovider", fileUri);
                    PhotoUtils.takePicture(UserInformation.this, imageUri, CODE_CAMERA_REQUEST);
                } else {
                    Toast.makeText(UserInformation.this, "设备没有SD卡！", Toast.LENGTH_SHORT).show();
                    Log.e("asd", "设备没有SD卡");
                }
            }

            @Override
            public void denied() {
                Toast.makeText(UserInformation.this, "Some permissions fail, and normal functions are affecte", Toast.LENGTH_LONG).show();
            }
        });

    }

    public void takePictureInAlbum(){
        requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, new ImageBaseActivity.RequestPermissionCallBack() {
            @Override
            public void granted() {
                PhotoUtils.openPic(UserInformation.this, CODE_GALLERY_REQUEST);
            }

            @Override
            public void denied() {
                Toast.makeText(UserInformation.this, "Some permissions fail, and normal functions are affected", Toast.LENGTH_LONG).show();
            }
        });
    }
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        return state.equals(Environment.MEDIA_MOUNTED);
    }

    public byte[] getBitmapByte(Bitmap bitmap) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
        return out.toByteArray();
    }
}

